package com.turbo.cloud.core.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.turbo.cloud.core.base.PageQuery;
import com.turbo.cloud.core.utils.BeanListUtils;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * 分页查询工具
 *
 * @author zhangluning
 */
public class PageQueryUtil {
    /**
     * 查询PageQuery 实体
     *
     * @param pageQuery      分页查询实体
     * @param targetSupplier 目标对象供应方
     * @return T
     */
    public static <T extends Serializable> T getPageParam(PageQuery<T> pageQuery, Supplier<T> targetSupplier) {
        T target = targetSupplier.get();
        return Objects.nonNull(pageQuery.getParam()) ? (T) pageQuery.getParam() : target;
    }

    /**
     * 查询PageQuery 实体
     *
     * @param page           分页查询实体
     * @param targetSupplier 目标对象供应方
     * @return T
     */
    public static <S extends Serializable, T extends Serializable> PageQuery<T> toPageQuery(Page<S> page, Supplier<T> targetSupplier) {
        PageQuery<T> pageQuery = new PageQuery<>();
        if (Objects.nonNull(page)) {
            BeanUtils.copyProperties(page, pageQuery);

            List<T> pageQueryRecords = new ArrayList<>();
            pageQuery.setRecords(pageQueryRecords);

            BeanListUtils.copyList(page.getRecords(), pageQuery.getRecords(), targetSupplier);
        }
        return pageQuery;
    }
}
